package com.example.controller;

import cn.hutool.core.bean.BeanUtil;
import com.example.domain.dto.*;
import com.example.domain.po.User;
import com.example.domain.vo.UserVo;
import com.example.service.UserService;
import com.example.util.AliOSSUtils;
import com.example.util.JwtUtil;
import com.example.util.PageBean;
import com.example.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private AliOSSUtils aliOSSUtils;

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @GetMapping("/setStudent")
    private Result<String> setStudent(Integer id) {
        userService.setStudent(id);
        return Result.success("成功设置身份为学生");
    }

    @GetMapping("/setDocker")
    private Result<String> setDocker(Integer id) {
        userService.setDocker(id);
        return Result.success("成功设置身份为医生");
    }


    @PostMapping("/userInfo")
    private User userInfo(@RequestHeader(name = "token") String token) {

        Map<String, Object> map = JwtUtil.parseToken(token);
        System.out.println(map);
        Integer userId = (Integer) map.get("userId");
        return userService.userInfo(userId);
    }

    @PostMapping("/login")
    private Result<String> login(@RequestBody LoginUser loginUser) {
        System.out.println(11111);

        //判断用户名是否存在
        User user = userService.findByPhone(loginUser.getPhone());

        if (user != null) { //数据库有该手机号
            //判断验证码
            if (loginUser.getCode().equals(stringRedisTemplate.opsForValue().get(loginUser.getPhone()))) {
                //验证码正确 登录成功
                //用户数据放到token里
                Map<String, Object> claims = new HashMap<>();
                claims.put("userId", user.getId());
                claims.put("username", user.getName());
                String token = JwtUtil.genToken(claims);
                //把token存储到redis里
                ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
                return Result.success(token);
            } else {
                //验证码错误
                return Result.error("验证码错误");
            }
        } else {
            //新用户
            // 先判断验证码有效否有效
            if (loginUser.getCode().equals(stringRedisTemplate.opsForValue().get(loginUser.getPhone()))) {  //用户传来的验证码和阿里的验证码一致
                //注册
              /*  var u = new User();
                u.setPhone(loginUser.getPhone());
                userService.add(u);
                Map<String, Object> claims = new HashMap<>();
                claims.put("userId", u.getId());
                claims.put("phone", u.getPhone());
                String token = JwtUtil.genToken(claims);
                ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
                operations.set(token, token, 48, TimeUnit.HOURS);
                return Result.success(token);*/
                return Result.error("新用户请先找管理员注册");
            } else {
                //手机号系统没有,验证码与短信发的不一致
                return Result.error("验证码错误");
            }

        }
    }


    @GetMapping("findByDepartmentId")
    public Result<List<User>> findByDepartmentId(Integer departmentId) {
        return Result.success(userService.findByDepartmentId(departmentId));
    }


    @GetMapping
    public Result<PageBean<UserVo>> list(
            Integer pageNum,
            Integer pageSize,
            Integer hospitalId,
            Integer departmentId,
            String name
    ) {
        return Result.success(userService.list(pageNum, pageSize, hospitalId, departmentId, name));
    }


    @PostMapping
    public Result<String> add(UserDTO dockerDTO) throws IOException {
        System.out.println(11);
        System.out.println(111);
        String photopath = aliOSSUtils.upload(dockerDTO.getPhotopath());
        User user = BeanUtil.copyProperties(dockerDTO, User.class);
        user.setPhotopath(photopath);
        userService.add(user);
        return Result.success("添加成功");
    }


    @PostMapping("/add2")
    public Result<String> add2(UserDTO3 dockerDTO) throws IOException {
        System.out.println(11);
        User user = BeanUtil.copyProperties(dockerDTO, User.class);
        user.setPhotopath("https://lmcacc.oss-cn-beijing.aliyuncs.com/default1.jpg");
        userService.add(user);
        return Result.success("添加成功");
    }


    @DeleteMapping("/{id}")
    public Result<String> del(@PathVariable("id") Integer id) {
        userService.del(id);
        return Result.success("删除成功");
    }

    @PutMapping
    public Result<String> update(UserDTO dockerDTO) throws IOException {
        String photopath = aliOSSUtils.upload(dockerDTO.getPhotopath());
        User user = BeanUtil.copyProperties(dockerDTO, User.class);
        user.setPhotopath(photopath);
        userService.update(user);
        return Result.success("修改成功");
    }

    @PutMapping("/raw")
    public Result<String> update2(UserDTO2 dockerDTO2) throws IOException {
        User user = BeanUtil.copyProperties(dockerDTO2, User.class);
        userService.update(user);
        return Result.success("修改成功");
    }

    /**
     * 根据症状、疾病、医院、科室、医生的姓名以及名字模糊获取医生集合
     *
     * @param name
     * @return
     */
    @GetMapping("/listByLike")
    public Result<List<Map<String, Object>>> listByLike(String name) {
        if (name == null)
            name = "";
        return Result.success(userService.listByLike(name));
    }


    /**
     * 分页列表
     */
    @GetMapping("/page")
    public Result<PageBean<User>> page(Integer role, String name, String phone, Integer pageNum, Integer pageSize) {
        return Result.success(userService.page(role, name, phone, pageNum, pageSize));
    }


    @PostMapping("/addAccount")
    public Result<String> addAccount(@RequestBody User user) {

        userService.addAccount(user);
        return Result.success("添加成功");

    }

    /**
     * 根据phone查询用户信息以及医院职位购课数
     *
     * @param phone
     * @return
     */
    @GetMapping("/getBylike")
    public Result<Map<String, Object>> getBylike(String phone) {
        return Result.success(userService.getBylike(phone));
    }

    /**
     * 下订单
     *
     * @param map
     * @return
     */
    @PostMapping("/payCourse")
    public Result<String> payCourse(@RequestBody Map<String, Long> map) {
        return Result.success(userService.payCourse(map.get("orderNo")));
    }

    /**
     * 用户详细信息编辑
     *
     * @return
     */
    @PostMapping("/editInfo")
    public Result<String> editInfo(@RequestBody User user) {
        userService.editInfo(user);
        return Result.success("修改成功");
    }

    /**
     * 通过phone查找用户信息
     *
     * @param phone
     * @return
     */
    @GetMapping("/getByPhone")
    public Result<User> getByPhone(String phone) {
        return Result.success(userService.getByPhone(phone));
    }

    @PostMapping("/uploadAvatar")
    public Result<String> uploadAvatar(MultipartFile file) throws IOException {
        System.out.println(file);
        var s = aliOSSUtils.upload(file) ;
        System.out.println(s);
        try {
            return Result.success(new AliOSSUtils().upload(file));
        }catch (Exception e){
            System.out.println(112233);
            return Result.success(s);
        }
    }
}
